<?php


namespace app\crm\model;

use app\common\traits\ActionRecordTrait;
use mysql_xdevapi\Exception;
use think\facade\Db;
use app\admin\model\Common;

class MedicalRecords extends Common
{
    use ActionRecordTrait;
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'medical_records';

    function diag(){
        return $this->hasOne(MedicalRecordsDiag::class,'case_id','id');
    }
    function diags(){
        return $this->hasMany(MedicalRecordsDiag::class,'case_id','id');
    }
    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     */
    public function getDataList(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

            $customer_id       = isset($request['customer_id']) && trim($request['customer_id']) ? trim($request['customer_id']) : '';
            $where      = [];

            if(!empty($customer_id)){
                array_push($where, ['customer_id', '=', $customer_id]);
            }else{
                $data              = [];
                $data['list']      = $list ?? [];
                $data['dataCount'] = $dataCount ?? 0;
                return $data;
            }
            $dataCount = $this->where($where)->count();


            if ($dataCount >0 ) {
                $field = ['id', 'customer_id', 'customer_name', 'create_time', 'case_no', 'doctor_id','is_bargain','bargain_money'];
                $list  = $this->with(['diag'=>function($query)use($field){
                    $query->field('case_id,diagnose_category_three_text');
                }])->where($where)->field($field)->order('id','desc')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();

                $customer_ids = array_unique(array_column($list, 'customer_id'));
                $customerList  = Customer::whereIn('id', $customer_ids)->column('telephone', 'id');
                $doctor_ids = array_unique(array_column($list, 'doctor_id'));
                $doctorList = ShopPerson::whereIn('id',$doctor_ids)->column('name', 'id');
                foreach ($list as $key => &$val) {
                    $val['diagnose_category_three_text'] = !empty($val['diag'])?$val['diag']['diagnose_category_three_text']:'';
                    $val['telephone'] = $customerList[$val['customer_id']] ?? '';
                    $val['doctor_name'] = $doctorList[$val['doctor_id']] ?? '';
                    $val['is_bargain'] = $val['is_bargain'] ==1?'成交':'未成交';

                }
            }
            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }

    /**
     * 添加
     * @param  array $request 请求参数
     * @return bool
     */
    public function addCase(array $request): array
    {


        $validate = new \app\crm\validate\MedicalRecords();
        if (!$validate->scene('create')->check($request)) {
            throw new \Exception($validate->getError());
        }
        $time = time();
        $customer_id = $request['customer_id'];
        $customer = Customer::where('id',$customer_id)->find();
        $doctor_name = ShopPerson::where('id',$request['doctor_id'])->value('name');
        $data = [
            'customer_id' => intval($request['customer_id']),
            'customer_name'     => $customer['customer_name'],
            'customer_sex'      => $customer['sex'],
            'shop_id'           => $customer['shop_id'],
            'customer_birth_date' => $customer['birthday'],
            'doctor_id'     => trim($request['doctor_id']),
            'case_no'=> time().rand(10000,99999),
            'doctor_name'=>$doctor_name,
            'create_time'     => $time,
            'treatment_date'  => $time
        ];
        $sign_img = ShopPersonSign::where('person_id',$request['doctor_id'])->where('is_del',0)->where('is_default',1)->value('sign_img');
        $return_data = [
            'customer_name'=>$data['customer_name'],
            'case_no'=>$data['case_no'],
            'customer_sex_text'=>$data['customer_sex']=='1'?'男':'女',
            'customer_birth_date'=>date('Y-m-d',$data['customer_birth_date']),
            'doctor_name'=>$doctor_name,
            'treatment_date'=>date('Y-m-d',$time),
            'sign_img'=>$sign_img
        ];
        $caseId = $this->insertGetId($data);
        if ($caseId >0) {
            $return_data['id']=$caseId;
            return $return_data;
        }else{
            throw new \Exception('创建病例失败');
        }

    }



    /**
     * 编辑病例
     * @param  array $request 请求参数
     * @return bool
     */
    public function saveCase(array $request): bool
    {

        Db::startTrans();
        try {
            $validate = new \app\crm\validate\MedicalRecords();
            if (!$validate->scene('update')->check($request)) {
                throw new \Exception($validate->getError());
            }

            $case_id = $request['id'];
            $customer_id = $request['customer_id'];
            $case = $this->where(['id' => $case_id,'customer_id'=>$customer_id])->find();
            if (empty($case)) {
                throw new \Exception('病例不存在');
            }

            $diag = $request['diag'] ??[];

            $item_type = DB::name('item_type')->column('name','id');
            $case->doctor_id  = $request['doctor_id'];
            $case->case_type  = $request['case_type'];
            $case->principle_action     = $request['principle_action']??'';
            $case->previous_allergy_history     = $request['previous_allergy_history']??'';
            $case->now_medical_history     = $request['now_medical_history']??'';
            $case->previous_history     = $request['previous_history']??'';
            $case->family_history     = $request['family_history']??'';
            $case->skin_examine     = $request['skin_examine']??'';
            $case->auxiliary_examine     = $request['auxiliary_examine']??'';
            if(empty($case->e_signature_doctor)){
                $case->e_signature_doctor = ShopPersonSign::where('person_id',$case->doctor_id)->where('is_default',1)->where('is_del',0)->value('sign_img');
            }

            if(!empty($diag)){
                //先删除后增加
                $insert_arr = [];
                $medicalRecordsDiagModel = new MedicalRecordsDiag();
                $diagdelDes = $medicalRecordsDiagModel->where('case_id',$case_id)->delete();
                foreach ($diag as $k=>$v){
                    $insert = [
                        'case_id'=> $case_id,
                        'diagnose_category_one'        => $v['diagnose_category_one']??'',
                        'diagnose_category_one_text'   => $item_type[$v['diagnose_category_one']]??'',
                        'diagnose_category_two'        => $v['diagnose_category_two']??'',
                        'diagnose_category_two_text'   => $item_type[$v['diagnose_category_two']]??'',
                        'diagnose_category_three'      => $v['diagnose_category_three']??'',
                        'diagnose_category_three_text' => $item_type[$v['diagnose_category_three']]??'',
                        'advice_doctor'                => $v['advice_doctor']??'',
                        'therapeutic_schedule'         => $v['therapeutic_schedule']??'',
                    ];
                    array_push($insert_arr,$insert);
                }
                $medicalRecordsDiagModel->saveAll($insert_arr);
            }
            $case->update_time     = time();
            $res =$case->save();
            if ($res) {
                Db::commit();
                return true;
            }else{
                throw new \Exception('病例未创建');
            }
        } catch (\Exception $e) {
            Db::robback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除
     * @param  array $request 请求参数
     * @return bool
     */
    public function deleteData(array $request): bool
    {
        try {
            $settingId = $request['id'] ?? 0;
            if (!$settingId) {
                $this->error = '参数错误';
                return false;
            }

            $list = $this->where('id', '=', $settingId)->select()->toArray();
            if (!$list) {
                $this->error = '请选择数据';
                return false;
            }

//            这里需要判断是否被用、如果被用到则不能删除

            $bool = $this->where('id', '=', $settingId)->delete();
            if ($bool) {
                $this->error = '删除成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '删除失败';
        return false;
    }

    /**
     * 查看详情
     * @param  array $request 请求参数
     * @return bool
     */
    public function caseDetail(array $request) :array
    {
        try {
            $validate = new \app\crm\validate\MedicalRecords();
            if (!$validate->scene('detail')->check($request)) {
                throw new \Exception($validate->getError());
            }
            $case_id = $request['id'] ?? 0;
            $case = $this->with(['diags'=>function($query)use($case_id){
                $query->field('case_id,diagnose_category_one,diagnose_category_two,diagnose_category_three,advice_doctor,therapeutic_schedule');
            }])->where('id',$case_id)
                ->field('id,customer_id,customer_name,customer_sex,treatment_date,customer_birth_date,case_no,doctor_id,case_type,principle_action,previous_allergy_history,now_medical_history,previous_history,family_history,skin_examine,auxiliary_examine,doctor_name,e_signature_doctor')
                ->find();
            if(empty($case)){
                throw new \Exception('病例不存在');
            }
            $case = $case->toArray();

            foreach ($case['diags'] as $k=>&$v){
                $v['type'] = [
                    $v['diagnose_category_one'],$v['diagnose_category_two'],$v['diagnose_category_three']
                ];
            }

            //1 有  0 无
            $case['is_previous_history'] = empty($case['previous_allergy_history'])?0:1;
            $case['is_family_history'] = empty($case['family_history'])?0:1;

            $case['treatment_date'] = date('Y-m-d',$case['treatment_date']);
            $case['customer_birth_date'] = date('Y-m-d',$case['customer_birth_date']);
            return $case;

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }


    }




    /**
     * 病例变更记录
     * @param  array $request 请求参数
     * @return array
     */
    public function caseChangeLog(array $request): array
    {
        try {
            $validate = new \app\crm\validate\MedicalRecords();
            if (!$validate->scene('detail')->check($request)) {
                throw new \Exception($validate->getError());
            }
            $list = [
                [
                    'create_time'=>date('Y-m-d H:i:s'),
                    'change_log'=> '顾客姓名：张三,  诊断:病症2'
                ],
                [
                    'create_time'=>date('Y-m-d H:i:s'),
                    'change_log'=> '顾客姓名：张三,  诊断:病症2'
                ],
                [
                    'create_time'=>date('Y-m-d H:i:s'),
                    'change_log'=> '顾客姓名：张三,  诊断:病症3'
                ]
            ];

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;


        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }


    }

}
